package d6_groupChat;

import java.io.*;
import java.net.Socket;

public class ServerReaderThread extends Thread {
    private Socket socket;
    public ServerReaderThread(Socket socket) {
        this.socket = socket;
    }
    @Override
    public void run() {
        try {
            InputStream is = socket.getInputStream();//创建字节输入流
            DataInputStream dis = new DataInputStream(is);//转换为数据输入流
            while (true) {
                try {
                    String msg = dis.readUTF();
                    System.out.println(msg);
                    //把消息分发给所有客户端
                    sendMsgToAll(msg);
                } catch (IOException e) {
                    System.out.println(socket.getRemoteSocketAddress()+"line break"+e.getMessage());
                    Server.onLineSockets.remove(socket);
                    dis.close();
                    socket.close();
                    break;
                }
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

    }

    private void sendMsgToAll(String msg) {
        for (Socket socket : Server.onLineSockets) {
            try {
                OutputStream os = socket.getOutputStream();
                DataOutputStream dos = new DataOutputStream(os);
                dos.writeUTF(msg);
                dos.flush();//刷新内存
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
    }
}
